package com.tlias.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * 阿里云OSS操作工具类
 */
@Slf4j
public class AliyunOSSUtils {

    /**
     * 上传文件到阿里云OSS
     * @param endpoint OSS服务地址，例如：String endpoint = "https://oss-cn-beijing.aliyuncs.com";
     * @param bucketName 存储空间（Bucket）名称 String bucketName = "lyx-student";
     * @param content 文件内容的字节数组
     * @param extName 文件名，如"1.jpg"
     * @return 返回文件的访问URL
     * @throws Exception
     */
    public static String upload(String endpoint, String bucketName, byte[] content, String extName) throws Exception {
        // 从环境变量中读取阿里云凭证，需提前设置OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 使用UUID+扩展名生成唯一文件名，避免重复覆盖
        // 将文件放在 image/ 目录下
        String objectName = "image/"+ UUID.randomUUID()+extName;

        // 创建OSS客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // 构建上传请求对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));

            // 执行上传操作
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            // OSS服务端错误，比如权限问题、Bucket不存在等
            log.error("OSS服务端错误: {}", oe.getErrorMessage());
            log.error("错误码: {}, 请求ID: {}", oe.getErrorCode(), oe.getRequestId());
        } catch (ClientException ce) {
            // 客户端网络通信异常
            log.error("客户端通信错误: {}", ce.getMessage());
        } finally {
            // 关闭客户端，释放资源
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 拼接文件访问URL
        //返回对应的文件访问URL拿到后可以访问上传文件的地址
        String[] parts = endpoint.split("//");
        return parts[0] + "//" + bucketName + "." + parts[1] + "/" + objectName;
    }
}
